using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using Celestus.Iis.Filters;

namespace Celestus.Iis.Modules
{
    /// <summary>
    /// Enables word wrap of plain text.
    /// </summary>
    public class TextWrapperModule : IHttpModule
    {
        #region IHttpModule Members
        
        /// <summary>
        /// Initializes this module instance and prepares it to handle requests.
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            context.PostRequestHandlerExecute += new EventHandler(context_PostRequestHandlerExecute);
        }

        /// <summary>
        /// Enables word wrap of plain text responses.
        /// </summary>
        void context_PostRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = app.Context;
            string mimeType = context.Response.Headers["Content-Type"];

            if (mimeType == "text/plain")
            {
                int lineLength;
                bool enabled = context.Request.QueryString["e"] != "f";

                if (!int.TryParse(context.Request.QueryString["l"], out lineLength))
                {
                    lineLength = 80;
                }
                if (lineLength <= 0)
                {
                    lineLength = 80;
                }
                if (enabled)
                {
                    context.Response.Filter = new TextWrapperFilter(context.Response.Filter, lineLength);
                }
            }
        }

        /// <summary>
        /// Releases all resources used by this module instance.
        /// </summary>
        public void Dispose()
        { 
        }

        #endregion
    }
}
